package cn.jetpiece.cloud.common.app.modular.message.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.NumberUtil;
import cn.jetpiece.cloud.common.api.message.MessageConfigApi;
import cn.jetpiece.cloud.common.api.message.model.params.CreateMessageConfigParam;
import cn.jetpiece.cloud.common.api.message.model.params.UpdateMessageConfigParam;
import cn.jetpiece.cloud.common.api.message.model.query.MessageConfigQuery;
import cn.jetpiece.cloud.common.api.message.model.result.MessageConfigResult;
import cn.jetpiece.cloud.common.app.modular.message.entity.MessageConfig;
import cn.jetpiece.cloud.common.app.modular.message.service.IMessageConfigService;
import cn.jetpiece.cloud.common.app.modular.message.wrapper.MessageConfigWrapper;
import cn.jetpiece.cloud.core.page.PageFactory;
import cn.jetpiece.cloud.core.query.QueryGenerator;
import cn.jetpiece.cloud.core.util.HttpContext;
import cn.jetpiece.cloud.model.page.PageResult;
import cn.jetpiece.cloud.model.response.Result;
import cn.jetpiece.cloud.starter.app.modular.base.controller.BaseController;
import cn.zyszkj.aiot.sdk.common.CommonResult;
import cn.zyszkj.aiot.sdk.common.PageResponse;
import cn.zyszkj.aiot.sdk.common.page.QueryParam;
import cn.zyszkj.aiot.sdk.model.notify.NotifyConfigInfo;
import cn.zyszkj.aiot.sdk.model.notify.NotifyTemplateInfo;
import cn.zyszkj.aiot.sdk.model.notify.NotifyTypeInfo;
import cn.zyszkj.aiot.sdk.service.NotifyService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 消息配置
 *
 * @author jetpiece
 * @since 2022-11-22
 */
@Slf4j
@RestController
@RequiredArgsConstructor
public class MessageConfigController extends BaseController<MessageConfig, IMessageConfigService> implements MessageConfigApi {
    private static final NotifyService notifyService = new NotifyService();
    private final IMessageConfigService messageConfigService;

    @Override
    public Result<String> add(CreateMessageConfigParam param) {
        try {
            MessageConfig messageConfig = BeanUtil.toBean(param, MessageConfig.class);
            if (messageConfigService.save(messageConfig)) {
                return Result.OK("添加成功!");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return Result.error("添加失败");
    }

    @Override
    public Result<String> update(UpdateMessageConfigParam param) {
        try {
            MessageConfig oldBean = messageConfigService.getById(param.getId());
            if (oldBean == null) {
                return Result.error("数据未找到!");
            }
            MessageConfig messageConfig = BeanUtil.toBean(param, MessageConfig.class);
            if (messageConfigService.updateById(messageConfig)) {
                return Result.OK("编辑成功!");
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return Result.error("编辑失败");
    }

    @Override
    public Result<String> delete(Long id) {
        try {
            if (messageConfigService.removeById(id)) {
                return Result.OK("删除成功!");
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return Result.error("删除失败");
    }

    @Override
    public Result<String> deleteBatch(String ids) {
        try {
            List<Long> idList = Convert.toList(Long.class, ids.split(","));
            if (messageConfigService.removeByIds(idList)) {
                return Result.OK("批量删除成功!");
            }
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return Result.error("批量删除失败");
    }

    @Override
    public Result<MessageConfigResult> get(Long id) {
        try {
            MessageConfig messageConfig = messageConfigService.getById(id);
            if (messageConfig == null) {
                return Result.error("数据未找到!");
            }
            return Result.OK(BeanUtil.toBean(messageConfig, MessageConfigResult.class));
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return Result.error("获取数据失败！");
    }

    @Override
    public Result<PageResult<MessageConfigResult>> page(MessageConfigQuery query) {
        MessageConfig messageConfig = BeanUtil.toBean(query, MessageConfig.class);
        QueryWrapper<MessageConfig> queryWrapper = QueryGenerator.initQueryWrapper(messageConfig, HttpContext.getRequestParameters());
        Page<MessageConfig> page = PageFactory.defaultPage();
        IPage<MessageConfig> pageList = messageConfigService.page(page, queryWrapper);
        return Result.OK(new MessageConfigWrapper(pageList).setWrapper(true).wrapPageResult());
    }

    @Override
    public Result<String> importExcel(MultipartHttpServletRequest request) {
        return super.importXls(request);
    }

    @Override
    public ModelAndView exportExcel(MessageConfigQuery query) {
        return super.exportXls(query, MessageConfigResult.class, "消息配置");
    }

    @Override
    public Result<PageResult<Map<String, Object>>> notifyTypes() {
        CommonResult<List<NotifyTypeInfo>> result = notifyService.getAllTypes();
        if (result.isSuccess()) {
            List<Map<String, Object>> resultMap = new ArrayList<>();
            result.getResult().forEach(item -> resultMap.add(BeanUtil.beanToMap(item)));
            PageResult<Map<String, Object>> pageResult = new PageResult<>(1, resultMap.size(), resultMap.size());
            pageResult.setRows(resultMap);
            return Result.OK(pageResult);
        } else {
            return Result.error("获取通知类型失败");
        }
    }

    @Override
    public Result<PageResult<Map<String, Object>>> notifyConfigPage(String notifyType) {
        IPage<Object> iPage = PageFactory.defaultPage();
        QueryParam queryParam = new QueryParam();
        queryParam.setPageIndex(Math.toIntExact(iPage.getCurrent()));
        queryParam.setPageSize(Math.toIntExact(iPage.getSize()));
        CommonResult<PageResponse<NotifyConfigInfo>> result = notifyService.queryNotifyConfigForPage(queryParam, notifyType);
        if (result.isSuccess()) {
            PageResponse<NotifyConfigInfo> notifyConfigInfoPageResponse = result.getResult();
            PageResult<Map<String, Object>> pageResult = new PageResult<>(notifyConfigInfoPageResponse.getPageIndex(), notifyConfigInfoPageResponse.getPageSize(), notifyConfigInfoPageResponse.getTotal());
            List<Map<String, Object>> resultMap = new ArrayList<>();
            notifyConfigInfoPageResponse.getData().forEach(item -> resultMap.add(BeanUtil.beanToMap(item)));
            pageResult.setRows(resultMap);
            return Result.OK(pageResult);
        } else {
            return Result.error("获取通知类型失败");
        }
    }

    @Override
    public Result<PageResult<Map<String, Object>>> notifyTemplatePage(String notifyType) {
        IPage<Object> iPage = PageFactory.defaultPage();
        QueryParam queryParam = new QueryParam();
        queryParam.setPageIndex(Math.toIntExact(iPage.getCurrent()));
        queryParam.setPageSize(Math.toIntExact(iPage.getSize()));
        CommonResult<PageResponse<NotifyTemplateInfo>> result = notifyService.queryNotifyTemplateForPage(queryParam, notifyType);
        if (result.isSuccess()) {
            PageResponse<NotifyTemplateInfo> notifyTemplatePage = result.getResult();
            PageResult<Map<String, Object>> pageResult = new PageResult<>(notifyTemplatePage.getPageIndex(), notifyTemplatePage.getPageSize(), notifyTemplatePage.getTotal());
            List<Map<String, Object>> resultMap = new ArrayList<>();
            notifyTemplatePage.getData().forEach(item -> resultMap.add(BeanUtil.beanToMap(item)));
            pageResult.setRows(resultMap);
            return Result.OK(pageResult);
        } else {
            return Result.error("获取通知模板失败");
        }
    }

    @Override
    public Result<Map<String, Object>> template(String templateId) {
        CommonResult<NotifyTemplateInfo> result = notifyService.getTemplate(templateId);
        if (result.isSuccess()) {
            return Result.OK(BeanUtil.beanToMap(result.getResult()));
        } else {
            return Result.error("获取通知类型失败");
        }
    }

    @Override
    public Result<Object> sendById(Long id, Map<String, Object> params) {
        MessageConfig messageConfig = messageConfigService.getById(id);
        if (messageConfig == null) {
            return Result.error("数据未找到!");
        }
        CommonResult<Object> result = notifyService.sendNotify(messageConfig.getNotifyConfig(), messageConfig.getTemplateCode(), params);
        if (result.isSuccess()) {
            return Result.OK("发送成功！", result.getResult());
        } else {
            if (NumberUtil.isInteger(result.getCode())) {
                return Result.error(Integer.parseInt(result.getCode()), result.getMessage());
            } else {
                return Result.error("发送失败");
            }
        }
    }

    @Override
    public Result<Object> send(String notifyConfigId, String templateId, Map<String, Object> params) {
        CommonResult<Object> result = notifyService.sendNotify(notifyConfigId, templateId, params);
        if (result.isSuccess()) {
            return Result.OK("发送成功！", result.getResult());
        } else {
            if (NumberUtil.isInteger(result.getCode())) {
                return Result.error(Integer.parseInt(result.getCode()), result.getMessage());
            } else {
                return Result.error("发送失败");
            }
        }
    }

}
